<template>
  <view class="participant-list">
    <view class="sort-option">
      <view @click="setSort('votes')" :class="{ active: sortBy === 'votes' }">按票数排序</view>
      <view @click="setSort('rank')" :class="{ active: sortBy === 'rank' }">按排名排序</view>
    </view>
    <view v-if="participants.length === 0" class="empty-list">
      <text class="fa fa-picture-o fa-3x"></text>
      <view class="empty-text">暂无项目数据</view>
    </view>
    <view
          class="participant-item"
          v-for="(item, index) in sortedParticipants"
          :key="item.projectId"
        >
          <view class="item-rank" :class="{'rank-top': index < 3}">
              <!-- 修改这里：前三名显示指定图片 -->
              <image 
                v-if="index < 3" 
                :src="`/static/img/no${index+1}.png`" 
                mode="aspectFit" 
                class="rank-image"
              ></image>
              <text v-else>NO.{{ index + 1 }}</text>
            </view>
      <view class="item-content">
        <view class="item-media">
          <image
            :src="item.image || 'https://via.placeholder.com/80'"
            mode="aspectFill"
            class="item-cover"
          ></image>
          <view class="item-vote-count">
            <text class="vote-number">{{ getTotalVotes(item) }}</text>
            <text class="vote-text">票</text>
          </view>
        </view>
        <view class="item-info">
          <view class="item-name">{{ item.name || '未命名项目' }}</view>
          <view class="vote-progress">
            <view class="progress-track">
              <view
                class="progress-bar"
                :style="{ width: item.votePercent + '%' }"
              ></view>
            </view>
            <view class="vote-percent">{{ item.votePercent }}%</view>
          </view>
        </view>
        <button 
          class="vote-btn" 
          @click="handleVote(item, index)"
          :disabled="isVotingEnded || item.loading || (getVoteStatus(item) === 'default' && remainingVotes <= 0)"
          :class="{ 
            'btn-vote': getVoteStatus(item) === 'default',
            'btn-cancel': getVoteStatus(item) === 'voted',
            'btn-loading': item.loading,
            'disabled-btn': remainingVotes <= 0 && getVoteStatus(item) === 'default'
          }"
        >
          <text v-if="item.loading">处理中...</text>
          <text v-else-if="getVoteStatus(item) === 'default' && remainingVotes > 0">投票</text>
          <text v-else-if="getVoteStatus(item) === 'default' && remainingVotes <= 0">票数已用完</text>
          <text v-else>取消投票</text>
          <text class="fa" 
            :class="item.loading ? 'fa-spinner fa-spin ml-1' : (getVoteStatus(item) === 'default' ? 'fa-heart-o ml-1' : 'fa-times ml-1')"></text>
        </button>
      </view>
    </view>
    <!-- 加载更多 -->
    <view class="load-more" @click="loadMore" :disabled="isVotingEnded || loading">
      <text v-if="loading">加载中...</text>
      <text v-else>加载更多</text>
      <text class="fa fa-angle-down ml-1"></text>
    </view>
  </view>
</template>

<script>
import { voteProject, cancelVoteProject } from '@/api/details.js'; 
export default {
  props: {
    participants: {
      type: Array,
      default: () => []
    },
    sortBy: {
      type: String,
      default: 'votes'
    },
    isVotingEnded: {
      type: Boolean,
      default: false
    },
    pageSize: {
      type: Number,
      default: 6
    },
    currentPage: {
      type: Number,
      default: 1
    },
    loading: {
      type: Boolean,
      default: false
    },
    remainingVotes: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      localVoteStatus: this.getSavedVoteStatus(),
      localSortBy: this.sortBy
    }
  },
  created() {
    window.addEventListener('beforeunload', this.saveVoteStatus);
  },
  beforeDestroy() {
    window.removeEventListener('beforeunload', this.saveVoteStatus);
    this.saveVoteStatus();
  },
  computed: {
    sortedParticipants() {
      // 确保participants存在且是数组
      if (!this.participants || !Array.isArray(this.participants)) {
        return [];
      }
      
      return [...this.participants].sort((a, b) => {
        if (this.localSortBy === 'votes') {
          // 使用总票数进行排序
          const totalVotesA = this.getTotalVotes(a);
          const totalVotesB = this.getTotalVotes(b);
          return totalVotesB - totalVotesA;
        } else {
          // 默认按ID排序
          return a.id - b.id;
        }
      });
    }
  },
  methods: {
    // 设置排序方式
    setSort(type) {
      this.localSortBy = type;
    },
    
    // 计算总票数（场外 + 场内）
    getTotalVotes(item) {
      return (item.totalVotes || 0) + (item.totalInsideVotes || 0);
    },
    
    // 从本地存储获取投票状态
    getSavedVoteStatus() {
      try {
        const saved = localStorage.getItem('voteStatus');
        return saved ? JSON.parse(saved) : {};
      } catch (error) {
        console.error('获取本地投票状态失败:', error);
        return {};
      }
    },
    
    // 保存投票状态到本地存储
    saveVoteStatus() {
      try {
        localStorage.setItem('voteStatus', JSON.stringify(this.localVoteStatus));
      } catch (error) {
        console.error('保存本地投票状态失败:', error);
      }
    },
    
    // 获取投票状态（优先使用本地状态）
    getVoteStatus(item) {
      // 确保项目有voteStatus属性，如果没有则使用默认值
      const itemStatus = item.voteStatus || 'default';
      return this.localVoteStatus[item.projectId] || itemStatus;
    },
    
    async handleVote(item, index) {
          if (this.isVotingEnded || item.loading) {
            this.$emit('showToast', 'info', this.isVotingEnded ? '投票已结束，感谢参与！' : '操作处理中，请稍候...');
            return;
          }
    
          const currentStatus = this.getVoteStatus(item);
          const newStatus = currentStatus === 'default' ? 'voted' : 'default';
    
          // 使用Vue的$set确保响应式更新
          this.$set(this.localVoteStatus, item.projectId, newStatus);
          this.saveVoteStatus(); // 立即保存到本地存储
    
          // 创建临时数组更新加载状态
          const updatedParticipants = [...this.participants];
          updatedParticipants[index] = {
            ...updatedParticipants[index],
            loading: true
          };
    
          // 触发父组件更新UI
          this.$emit('updateParticipants', updatedParticipants);
    
          try {
            let success = false;
            let message = '';
    
            if (currentStatus === 'default') {
              // 执行投票
              const response = await voteProject({ projectId: item.projectId });
    
              if (response.code === 200) {
                success = true;
                message = '投票成功！';
              } else {
                message = response.msg || '投票失败，请稍后重试';
              }
            } else {
              // 执行取消投票
              const response = await cancelVoteProject({ projectId: item.projectId });
    
              if (response.code === 200) {
                success = true;
                message = '取消投票成功！';
              } else {
                message = response.msg || '取消投票失败，请稍后重试';
              }
            }
    
            if (success) {
              // 成功后更新数据
              const newParticipants = [...updatedParticipants];
              newParticipants[index] = {
                ...newParticipants[index],
                loading: false,
                voteStatus: newStatus,
                // 更新场外投票数
                totalVotes: (newParticipants[index].totalVotes || 0) + (currentStatus === 'default' ? 1 : -1)
              };
    
              // 通知父组件更新数据
              this.$emit('updateParticipants', newParticipants);
              this.$emit('showToast', 'success', message);
              // 触发自定义事件通知父组件更新总票数
              this.$emit('updateVoteStats', newParticipants);
    
              // 通过WebSocket发送投票更新消息
              const client = window.client;
              if (client && client.connected) {
                  client.send('/app/voteUpdate', {}, JSON.stringify(newParticipants));
              }
            } else {
              // 失败时回滚本地状态
              // 修改部分：使用 delete 关键字删除属性
              delete this.localVoteStatus[item.projectId];
              this.saveVoteStatus(); // 保存回滚后的状态
              this.handleError(updatedParticipants, index, message);
            }
          } catch (error) {
            // 失败时回滚本地状态
            // 修改部分：使用 delete 关键字删除属性
            delete this.localVoteStatus[item.projectId];
            this.saveVoteStatus(); // 保存回滚后的状态
            this.handleError(updatedParticipants, index, '网络错误，请稍后重试');
          }
        },
    
    handleError(participants, index, message) {
      // 恢复加载状态
      const newParticipants = [...participants];
      newParticipants[index] = {
        ...newParticipants[index],
        loading: false
      };
      
      // 通知父组件更新数据
      this.$emit('updateParticipants', newParticipants);
      this.showToast('error', message);
    },
    
    showToast(type, message) {
      uni.showToast({
        title: message,
        icon: type === 'success' ? 'success' : 'none',
        duration: 2000
      });
    },
    
    loadMore() {
      this.$emit('loadMore');
    }
  }
}
</script>

<style scoped>
/* 添加排名图片样式 */
.rank-image {
  width: 32px;
  height: 32px;
}

/* 调整排名容器样式 */
.item-rank {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  /* 移除圆形背景 */
  background-color: transparent !important;
}

/* 移除原有的排名图标样式 */
.rank-icon {
  display: none;
}	
	
/* 选手列表 */
.participant-list {
  padding: 0 16px 16px;
  background-color: #fff;
  margin-bottom: 12px;
}

.sort-option {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  font-size: 14px;
}

.sort-option > view {
  margin-left: 15px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.sort-option > view.active {
  background-color: #f56c6c;
  color: white;
}

.empty-list {
  padding: 40px 0;
  text-align: center;
  color: #999;
}

.empty-text {
  margin-top: 10px;
  font-size: 16px;
}
.participant-item {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid #eee;
}
.item-rank {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f5f5f5;
  color: #666;
  font-size: 14px;
  font-weight: bold;
  margin-right: 12px;
}
.rank-top {
  background-color: #ff3b30;
  color: #fff;
}
.rank-icon {
  font-size: 16px;
}
.text-yellow {
  color: #ffd700;
}
.text-silver {
  color: #c0c0c0;
}
.text-bronze {
  color: #cd7f32;
}
.item-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item-media {
  position: relative;
  margin-right: 12px;
}
.item-cover {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.item-vote-count {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 12px;
  text-align: center;
  padding: 4px 0;
  border-radius: 0 0 4px 4px;
}
.vote-number {
  font-weight: bold;
}
.item-info {
  flex: 1;
  max-width: calc(100% - 140px);
}
.item-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.vote-progress {
  display: flex;
  align-items: center;
}
.progress-track {
  flex: 1;
  height: 6px;
  background-color: #eee;
  border-radius: 3px;
  overflow: hidden;
  margin-right: 8px;
}
.progress-bar {
  height: 100%;
  background-color: #ff3b30;
  border-radius: 3px;
  transition: width 0.3s ease;
}
.vote-percent {
  font-size: 12px;
  color: #666;
  min-width: 40px;
  text-align: right;
}
/* 投票按钮样式 */
.vote-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  transition: all 0.2s ease;
  min-width: 80px;
}
.btn-vote {
  background-color: #ff3b30;
  color: #fff;
}
.btn-vote:hover {
  background-color: #e02020;
}
.btn-cancel {
  background-color: #ff9500;
  color: #fff;
}
.btn-cancel:hover {
  background-color: #ff7700;
}
.btn-loading {
  background-color: #ccc;
  cursor: not-allowed;
}
.disabled-btn {
  background-color: #e0e0e0;
  color: #999;
  cursor: not-allowed;
}
.disabled-btn .fa-heart-o {
  color: #999;
}
.load-more {
  text-align: center;
  padding: 16px 0;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s ease;
}
.load-more:hover {
  color: #ff3b30;
}
.load-more:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>